package com.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.db.Db;
import cn.hutool.db.DbUtil;
import cn.hutool.db.meta.TableType;
import com.common.GeneratorTemplate;
import com.common.R;
import com.consts.GenerateConsts;
import com.entity.generate.GenerateParameters;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicParameters;
import com.utils.Generator1;
import com.utils.Generator2;
import com.utils.MetaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.Map;

/**
 * @ClassName GenerateController
 * @Description TODO
 * @Author 谭庆伟
 * @Date 2020/9/4 14:05
 * @Version 1.0
 **/
@SuppressWarnings("ALL")
@RestController
@RequestMapping(value = "/api/generate")
public class GenerateController {
    @Autowired
    private GeneratorTemplate generatorTemplate;
    @Autowired
    private MetaUtil metaUtil;
    @Autowired
    private DataSource dataSource;
    @RequestMapping(value = "/createService")
    @ResponseBody
    public R createService(@RequestBody Map<String,Object> map) throws SQLException {
        Generator2 generator2 = new Generator2(generatorTemplate, metaUtil, map);
        String[] split = "Mapper,Dao,Service,ServiceImpl,Entity,Field,Controller,Add,Edit,Index,IndexJs,vueConfigJsNext".split(",");
        for (String s : split) {
            generator2.writeServiceFile(s);
        }
        return R.ok(null);
    }
    @RequestMapping(value = "/checkIDs")
    @ResponseBody
    public R checkIDs() throws SQLException {

        return R.ok(null);
    }

    @PostMapping(value = "/getDbs")
    @ResponseBody
    public R getDbs() throws SQLException {
        Connection connection = dataSource.getConnection();
        String schema = connection.getSchema();
        DatabaseMetaData metaData = connection.getMetaData();
        ResultSet catalogs = metaData.getCatalogs();

        ArrayList<String> dbNames = new ArrayList<>();
        while (catalogs.next()) {
            String dbName = catalogs.getString(1);
            dbNames.add(dbName);
        }
        //connection.close();
        return R.ok(dbNames);
    }
    @PostMapping(value = "/getTables")
    @ResponseBody
    public R getTables(String dbName) throws SQLException {

        Connection connection = dataSource.getConnection();
        String schema = connection.getSchema();
        DatabaseMetaData metaData = connection.getMetaData();
        ResultSet catalogs = metaData.getCatalogs();

        ArrayList<String> tableNames = new ArrayList<>();
        ResultSet rs = metaData.getTables(dbName, schema, null,
                new String[]{TableType.TABLE.value()});
        while(rs.next()) {
            String tableName = rs.getString("TABLE_NAME");
            tableNames.add(tableName);
        }
        return R.ok(tableNames);
    }
    @PostMapping(value = "/createAllFiles")
    @ResponseBody
    public String createAllFiles(String packageName,String templatePath,String writePath,String vuePath,String dbName,String[] tableNames) {
        for (int i = 0; i < tableNames.length; i++) {
            Generator1 generator = new Generator1(metaUtil,packageName,dbName,tableNames[i],templatePath,writePath,vuePath);
            generator.createMapper();
            generator.createDao();
            generator.createService();
            generator.createServiceImpl();
            generator.createController();
            generator.createAdd();
            generator.createEdit();
            generator.createIndex();
            generator.createIndexJs();
            generator.addConfigJsNext();
            generator.addRouterMapJsNext();
        }
        GenerateConsts.writeAllConfigJs(templatePath,vuePath);
        GenerateConsts.writeAllRouterMapJs(templatePath,vuePath);
        return "操作成功";
    }

    @PostMapping(value = "/createFiles")
    @ApiOperationSupport(params = @DynamicParameters(properties = {
            @DynamicParameter(name = "tableName", value = "",example = "act_app_appdef"),
            @DynamicParameter(name = "templatePath", value = "",example = "D:\\data\\gitee\\generator\\src\\main\\resources\\templates\\"),
            @DynamicParameter(name = "writePath", value = "",example = "D:\\data\\gitee\\spring-boot-integration\\src\\main\\java\\com\\xius\\"),
            @DynamicParameter(name = "vuePath", value = "",example = "D:\\data\\gitee\\code_genertate\\"),
            @DynamicParameter(name = "fileTypes",
                    value ="",
                    example = "Mapper,Dao,Service,ServiceImpl,Entity,Field,Controller,Add,Edit,Index,IndexJs,ConfigJsNext,"
            )
    }
    ))
    @ResponseBody
    public R createFiles(@RequestBody Map<String,Object> map) throws SQLException {
        String tableName = (String) map.get("tableName");
        String dbName = (String) map.get("dbName");
        String templatePath = (String) map.get("templatePath");
        String writePath = (String) map.get("writePath");
        String vuePath = (String) map.get("vuePath");
        String packageName = (String) map.get("packageName");
        Generator1 generator = new Generator1(metaUtil,packageName,dbName,tableName,templatePath,writePath,vuePath);
        if(ObjectUtil.isNotEmpty((String) map.get("Mapper"))){
            generator.createMapper();
        }
        if(ObjectUtil.isNotEmpty((String) map.get("Dao"))){
            generator.createDao();
        }
        if(ObjectUtil.isNotEmpty((String) map.get("Service")) ){
            generator.createService();
        }
        if(ObjectUtil.isNotEmpty((String) map.get("ServiceImpl"))){
            generator.createServiceImpl();
        }
        if(ObjectUtil.isNotEmpty((String) map.get("Entity"))){
            generator.createEntity();
        }
        if(ObjectUtil.isNotEmpty((String) map.get("Field")) ){
            generator.createField();
        }
        if(ObjectUtil.isNotEmpty((String) map.get("Controller"))){
            generator.createController();
        }
        if(ObjectUtil.isNotEmpty((String) map.get("Add"))){
            generator.createAdd();
        }
        if(ObjectUtil.isNotEmpty((String) map.get("Edit"))){
            generator.createEdit();
        }
        if(ObjectUtil.isNotEmpty((String) map.get("Index"))){
            generator.createIndex();
        }
        if(ObjectUtil.isNotEmpty((String) map.get("IndexJs"))){
            generator.createIndexJs();
        }
        if(ObjectUtil.isNotEmpty((String) map.get("ConfigJsNext"))){
            generator.addConfigJsNext();
            GenerateConsts.writeAllConfigJs(templatePath,vuePath);
        }
        //权限表中自动加数据，自动在admin中加关联数据
        Connection connection = dataSource.getConnection();
        Statement statement = connection.createStatement();
        connection.setAutoCommit(false);
        GenerateParameters parameters = generator.getParameters();
        //表注释
        String tableComment = parameters.getTableComment();
        String className = parameters.getClassName();
        String page = "1";
        String btn  = "2";
        Snowflake snowflakeId = IdUtil.createSnowflake(1, 1);
        String parentId = snowflakeId.nextIdStr();
        StrBuilder insertPermisionPage = insertPermisionPage(parentId,tableComment,className);
        System.out.println(insertPermisionPage);
        boolean execute = statement.execute(insertPermisionPage.toString());

        StrBuilder queryAllByLimit = insertPermisionBtn(snowflakeId.nextIdStr(),tableComment, className, "queryAllByLimit", parentId);
        statement.execute(queryAllByLimit.toString());
        StrBuilder insert = insertPermisionBtn(snowflakeId.nextIdStr(),tableComment, className, "insert", parentId);
        statement.execute(insert.toString());
        StrBuilder inserts = insertPermisionBtn(snowflakeId.nextIdStr(),tableComment, className, "inserts", parentId);
        statement.execute(inserts.toString());
        StrBuilder queryById = insertPermisionBtn(snowflakeId.nextIdStr(),tableComment, className, "queryById", parentId);
        statement.execute(queryById.toString());
        StrBuilder update = insertPermisionBtn(snowflakeId.nextIdStr(),tableComment, className, "update", parentId);
        statement.execute(update.toString());
        StrBuilder deleteById = insertPermisionBtn(snowflakeId.nextIdStr(),tableComment, className, "deleteById", parentId);
        statement.execute(deleteById.toString());
        StrBuilder deleteByIds = insertPermisionBtn(snowflakeId.nextIdStr(),tableComment, className, "deleteByIds", parentId);
        statement.execute(deleteByIds.toString());
        StrBuilder queryAllJoin = insertPermisionBtn(snowflakeId.nextIdStr(),tableComment, className, "queryAllJoin", parentId);
        statement.execute(queryAllJoin.toString());
        StrBuilder queryAll = insertPermisionBtn(snowflakeId.nextIdStr(),tableComment, className, "queryAll", parentId);
        statement.execute(queryAll.toString());
        System.out.println(execute);
        connection.commit();
        connection.close();
        return R.ok("操作成功");
    }
    private StrBuilder insertPermisionPage(String snowflakeId,String tableComment,String className) throws SQLException {
        StrBuilder builder = new StrBuilder();
        String page = "1";
        String btn  = "2";
        builder.append("insert into sec_permission ");
        builder.append(" ("+"sec_permission_id,sec_permission_name,sec_permission_url,sec_permission_type,sec_permission_permission,sec_permission_method,sec_permission_sort,sec_permission_parent_id"+") ");
        builder.append(" values ");
        builder.append(" (");
        builder.append("'"+snowflakeId+"',");
        //sec_permission_name
        builder.append("'"+tableComment+"',");
        //url
        builder.append("'/api/"+className+"',");
        //type
        builder.append("'1',");
        //permmision 权限表达式
        builder.append("'page:"+ className+"',");
        //method
        builder.append("'',");
        //sort
        builder.append("'1',");
        //parent_id
        builder.append("'0'");
        builder.append(")");
        return builder;
    }
    private StrBuilder insertPermisionBtn(String snowflakeId,String tableComment,String className,String method, String parentID) throws SQLException {
        StrBuilder builder = new StrBuilder();
        String page = "1";
        String btn  = "2";
        builder.append("insert into sec_permission ");
        builder.append(" ("+"sec_permission_id,sec_permission_name,sec_permission_url,sec_permission_type,sec_permission_permission,sec_permission_method,sec_permission_sort,sec_permission_parent_id"+") ");
        builder.append(" values ");
        builder.append(" (");
        builder.append("'"+snowflakeId+"',");
        //sec_permission_name
        builder.append("'"+tableComment+"-"+method+"',");
        //url
        builder.append("'/api/"+className+"/"+method+"',");
        //type
        builder.append("'2',");
        //permmision 权限表达式
        builder.append("'btn:"+ className+":" + method+"',");
        //method
        builder.append("'POST',");
        //sort
        builder.append("'2',");
        //parent_id
        builder.append(parentID);
        builder.append(")");
        return builder;
    }

    @PostMapping(value = "/createQiNiuFiles")
    @ResponseBody
    public String createQiNiuFiles() {
        return null;
    }


}
